package com.example.myapplication.slice;

import com.example.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.TextField;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.rdb.ValuesBucket;
import ohos.data.resultset.ResultSet;
import ohos.utils.net.Uri;

public class RegisterAbilitySlice extends AbilitySlice {

    private DataAbilityHelper dataAbilityHelper;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_register);

        TextField tf1 = (TextField) findComponentById(ResourceTable.Id_register_name_textfield);
        TextField tf2 = (TextField) findComponentById(ResourceTable.Id_register_pwd_textfield);
        Button submitBtn = (Button) findComponentById(ResourceTable.Id_register_btn);

        submitBtn.setClickedListener(component -> {
            String inputUsername = tf1.getText();
            String inputPassword = tf2.getText();

            if (inputUsername == null || inputPassword == null) {
                new ToastDialog(this).setText("用户名或密码不能为空").show();
                return;
            }

            dataAbilityHelper = DataAbilityHelper.creator(this);
            Uri uri = Uri.parse("dataability:///com.example.myapplication.UserDataAbility/users1");

            // 创建ValuesBucket对象，用于存储要插入的数据
            ValuesBucket values = new ValuesBucket();
            values.putString("username", inputUsername);
            values.putString("password", inputPassword);

            try {
                int i= dataAbilityHelper.insert(uri,values);
                    // 插入成功
                    new ToastDialog(this).setText("注册成功!去登录吧").show();
                    // 清空输入框
                    tf1.setText("");
                    tf2.setText("");
                // 执行跳转操作
                present(new LoginAbilitySlice(), new Intent());

            } catch (DataAbilityRemoteException e) {
                // 插入数据时发生异常
                new ToastDialog(this).setText("注册失败，发生了数据异常").show();
                e.printStackTrace();
            }
        });
    }
}
